﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

using WebApi_SY.Models;
using WebApi_SY.Entity;     // 根据实际项目结构修改

namespace WebApi_SY.Controllers
{
    [RoutePrefix("api/sli-quality-模拟工艺单_锻造")]
    public class sli_quality_templateController : ApiController
    {
        private readonly YourDbContext _context = new YourDbContext();

        // 分页查询
        [HttpGet]
        [Route("Get模拟工艺单_锻造")]
        public IHttpActionResult Get模拟工艺单_锻造(int page = 1, int pageSize = 10)
        {
            try
            {
                IQueryable<sli_quality_template> query = _context.sli_quality_template;
                var totalCount = query.Count();
                var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);

                var result = query
                    .OrderByDescending(t => t.Id)
                    .Skip((page - 1) * pageSize)
                    .Take(pageSize)
                    .Select(t => new
                    {
                        t.Id,
                        t.FMetal,
                        t.FProductStandard,
                        t.FProductStatus,
                        t.FMaterialStandard,
                        t.FMaterial,
                        t.FTensile,
                        t.FImpact,
                        t.FHardness
                    });

                return Ok(new
                {
                    code = 200,
                    msg = "OK",
                    data = new
                    {
                        totalCount,
                        totalPages,
                        currentPage = page,
                        pageSize,
                        items = result
                    }
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // 根据ID查询
        [HttpGet]
        [Route("{id}")]
        public async Task<IHttpActionResult> GetTemplateById(int id)
        {
            try
            {
                var template = await _context.sli_quality_template
                    .FirstOrDefaultAsync(t => t.Id == id);

                if (template == null)
                {
                    return NotFound();
                }

                return Ok(new
                {
                    code = 200,
                    msg = "OK",
                    data = template
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // 新增
        [HttpPost]
        [Route("")]
        public async Task<IHttpActionResult> CreateTemplate([FromBody] sli_quality_template model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var newTemplate = new sli_quality_template
                {
                    FMetal = model.FMetal,
                    FProductStandard = model.FProductStandard,
                    FProductStatus = model.FProductStatus,
                    FMaterialStandard = model.FMaterialStandard,
                    FMaterial = model.FMaterial,
                    FTensile = model.FTensile,
                    FImpact = model.FImpact,
                    FHardness = model.FHardness
                };

                _context.sli_quality_template.Add(newTemplate);
                await _context.SaveChangesAsync();

                return CreatedAtRoute("DefaultApi", new { id = newTemplate.Id }, new
                {
                    code = 201,
                    msg = "Created",
                    data = newTemplate.Id
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // 更新
        [HttpPut]
        [Route("{id}")]
        public async Task<IHttpActionResult> UpdateTemplate(int id, [FromBody] sli_quality_template model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var existingTemplate = await _context.sli_quality_template
                    .FirstOrDefaultAsync(t => t.Id == id);

                if (existingTemplate == null)
                {
                    return NotFound();
                }

                // 更新字段
                existingTemplate.FMetal = model.FMetal;
                existingTemplate.FProductStandard = model.FProductStandard;
                existingTemplate.FProductStatus = model.FProductStatus;
                existingTemplate.FMaterialStandard = model.FMaterialStandard;
                existingTemplate.FMaterial = model.FMaterial;
                existingTemplate.FTensile = model.FTensile;
                existingTemplate.FImpact = model.FImpact;
                existingTemplate.FHardness = model.FHardness;

                await _context.SaveChangesAsync();

                return Ok(new
                {
                    code = 200,
                    msg = "Updated",
                    data = id
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        // 删除
        [HttpDelete]
        [Route("{id}")]
        public async Task<IHttpActionResult> DeleteTemplate(int id)
        {
            try
            {
                var template = await _context.sli_quality_template
                    .FirstOrDefaultAsync(t => t.Id == id);

                if (template == null)
                {
                    return NotFound();
                }

                _context.sli_quality_template.Remove(template);
                await _context.SaveChangesAsync();

                return Ok(new
                {
                    code = 200,
                    msg = "Deleted",
                    data = id
                });
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _context.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}